package cn.jiyun.ai.common.config;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
@Slf4j
public class JwtUtil {

    @Value("${emos.jwt.secret}")
    String secret;
    @Value("${emos.jwt.expire}")
    Integer expire;

    //根据userId ,生成token  userId + 日期 + 加密
    public String createToken(Integer userId) {
        // 创建加密算法
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 创建过期时间, offset 日期偏移
        DateTime date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, expire);
        // 创建JWT builder
        JWTCreator.Builder builder = JWT.create();
        // 生成token
        String token = builder.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
        return token;
    }


    //根据token 获取userId
    public int getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asInt();
        } catch (Exception e) {
            throw new RuntimeException("令牌无效");
        }
    }

    //校验token 是否有效
    public void verifierToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(secret); // 创建加密算法对象
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            verifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new RuntimeException("令牌无效");
        }
    }

}
